<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="设备ID"
          clearable
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通道名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="通道名称"
          clearable
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="厂商" prop="manufacturer">
        <el-input
          v-model="queryParams.manufacturer"
          placeholder="厂商"
          clearable
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="型号"
          clearable
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通道状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="通道状态"
          clearable
          style="width: 140px"
        >
          <el-option label="在线" value="ON"></el-option>
          <el-option label="离线" value="OFF"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="IP地址" prop="ipAddress">
        <el-input
          v-model="queryParams.ipAddress"
          placeholder="IP地址"
          clearable
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="安装地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="安装地址"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通道类型" prop="channelType">
        <el-select
          v-model="queryParams.channelType"
          placeholder="通道类型"
          clearable
          style="width: 140px"
        >
          <el-option label="未知" value="0"></el-option>
          <el-option label="视频" value="1"></el-option>
          <el-option label="音频" value="2"></el-option>
          <el-option label="物联网" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:wvpDeviceChannel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:wvpDeviceChannel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:wvpDeviceChannel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:wvpDeviceChannel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 批量操作区域 -->
    <div v-if="selectedChannels.length > 0" class="batch-actions">
      <el-alert 
        :title="`已选择 ${selectedChannels.length} 个通道`" 
        type="info" 
        :closable="false"
        style="margin-bottom: 15px;"
      >
        <template slot="default">
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span>已选择 {{ selectedChannels.length }} 个通道</span>
            <div>
              <el-button 
                size="mini" 
                type="danger" 
                @click="handleBatchDelete"
                v-hasPermi="['system:wvpDeviceChannel:remove']"
              >批量删除</el-button>
              <el-button size="mini" @click="clearSelection">取消选择</el-button>
            </div>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- 卡片式布局 -->
    <div v-loading="loading" class="channel-cards-container">
      <div class="cards-grid">
        <el-card 
          v-for="channel in wvpDeviceChannelList" 
          :key="channel.id"
          class="channel-card"
          :class="{ 'selected': isChannelSelected(channel) }"
          shadow="hover"
          @click.native="toggleChannelSelection(channel)"
        >
          <!-- 卡片头部 -->
          <div class="card-header" slot="header">
            <div class="channel-title">
              <el-checkbox 
                :value="isChannelSelected(channel)"
                @change="toggleChannelSelection(channel)"
                @click.native.stop
              ></el-checkbox>
              <div class="title-content">
                <div class="channel-name">{{ channel.name || channel.deviceId }}</div>
                <div class="channel-id">设备ID：{{ channel.deviceId }}</div>
              </div>
              <el-tag 
                :type="channel.status === 'ON' ? 'success' : 'danger'" 
                size="small"
                class="status-tag"
              >
                {{ channel.status === 'ON' ? '在线' : '离线' }}
              </el-tag>
            </div>
          </div>

          <!-- 卡片内容 -->
          <div class="card-content">
            <!-- 基础信息 -->
            <div class="info-section">
              <h4 class="section-title">基础信息</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">厂商:</span>
                  <span class="value">{{ channel.manufacturer || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">型号:</span>
                  <span class="value">{{ channel.model || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">通道类型:</span>
                  <el-tag size="mini" :type="getChannelTypeColor(channel.channelType)">
                    {{ getChannelTypeText(channel.channelType) }}
                  </el-tag>
                </div>
                <div class="info-item">
                  <span class="label">云台类型:</span>
                  <span class="value">{{ getPtzTypeText(channel.ptzType) }}</span>
                </div>
              </div>
            </div>

            <!-- 网络配置 -->
            <div class="info-section">
              <h4 class="section-title">网络配置</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">IP地址:</span>
                  <span class="value">{{ channel.ipAddress || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">端口:</span>
                  <span class="value">{{ channel.port || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">分辨率:</span>
                  <span class="value">{{ channel.resolution || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">有音频:</span>
                  <el-tag :type="channel.hasAudio === '1' ? 'success' : 'info'" size="mini">
                    {{ channel.hasAudio === '1' ? '是' : '否' }}
                  </el-tag>
                </div>
              </div>
            </div>

            <!-- 位置信息 -->
            <div class="info-section">
              <h4 class="section-title">位置信息</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">安装地址:</span>
                  <span class="value">{{ channel.address || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">经度:</span>
                  <span class="value">{{ channel.longitude || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">纬度:</span>
                  <span class="value">{{ channel.latitude || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">归属:</span>
                  <span class="value">{{ channel.owner || '-' }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 卡片操作按钮 -->
          <div class="card-actions">
            <el-button
              size="mini"
              type="success"
              icon="el-icon-video-play"
              @click.stop="handlePlay(channel)"
              v-hasPermi="['system:wvpDeviceChannel:play']"
            >播放</el-button>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click.stop="handleUpdate(channel)"
              v-hasPermi="['system:wvpDeviceChannel:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click.stop="handleDelete(channel)"
              v-hasPermi="['system:wvpDeviceChannel:remove']"
            >删除</el-button>
          </div>
        </el-card>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && wvpDeviceChannelList.length === 0" class="empty-state">
        <el-empty description="暂无通道数据">
          <el-button type="primary" @click="handleAdd">添加第一个通道</el-button>
        </el-empty>
      </div>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备通道对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基础信息 -->
        <el-card shadow="never" style="margin-bottom: 15px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">基础信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="设备ID" prop="deviceId">
                <el-input v-model="form.deviceId" placeholder="设备ID" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="通道名称" prop="name">
                <el-input v-model="form.name" placeholder="通道名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="厂商" prop="manufacturer">
                <el-input v-model="form.manufacturer" placeholder="厂商" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="型号" prop="model">
                <el-input v-model="form.model" placeholder="型号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="通道类型" prop="channelType">
                <el-select v-model="form.channelType" placeholder="选择通道类型">
                  <el-option label="未知" value="0"></el-option>
                  <el-option label="视频" value="1"></el-option>
                  <el-option label="音频" value="2"></el-option>
                  <el-option label="物联网" value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="云台类型" prop="ptzType">
                <el-select v-model="form.ptzType" placeholder="选择云台类型">
                  <el-option label="未知" value="0"></el-option>
                  <el-option label="球机" value="1"></el-option>
                  <el-option label="半球" value="2"></el-option>
                  <el-option label="固定枪机" value="3"></el-option>
                  <el-option label="遥控枪机" value="4"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 网络配置 -->
        <el-card shadow="never" style="margin-bottom: 15px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">网络配置</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="IP地址" prop="ipAddress">
                <el-input v-model="form.ipAddress" placeholder="IP地址" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="端口号" prop="port">
                <el-input-number v-model="form.port" placeholder="端口号" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" type="password" placeholder="密码" show-password />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 位置信息 -->
        <el-card shadow="never" style="margin-bottom: 15px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">位置信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="经度" prop="longitude">
                <el-input-number v-model="form.longitude" placeholder="经度" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="纬度" prop="latitude">
                <el-input-number v-model="form.latitude" placeholder="纬度" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="安装地址" prop="address">
                <el-input v-model="form.address" placeholder="安装地址" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="行政区域" prop="civilCode">
                <el-input v-model="form.civilCode" placeholder="行政区域" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="警区" prop="block">
                <el-input v-model="form.block" placeholder="警区" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备归属" prop="owner">
                <el-input v-model="form.owner" placeholder="设备归属" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 媒体设置 -->
        <el-card shadow="never" style="margin-bottom: 15px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">媒体设置</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="分辨率" prop="resolution">
                <el-input v-model="form.resolution" placeholder="分辨率" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="有音频" prop="hasAudio">
                <el-switch 
                  v-model="form.hasAudio" 
                  active-value="1" 
                  inactive-value="0"
                  active-text="是" 
                  inactive-text="否">
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="流ID" prop="streamId">
                <el-input v-model="form.streamId" placeholder="流ID" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下载速度" prop="downloadSpeed">
                <el-input-number v-model="form.downloadSpeed" placeholder="下载速度" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务分组ID" prop="businessGroupId">
                <el-input v-model="form.businessGroupId" placeholder="业务分组ID" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="录像计划ID" prop="recordPlanId">
                <el-input v-model="form.recordPlanId" placeholder="录像计划ID" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 设备属性 -->
        <el-card shadow="never" style="margin-bottom: 15px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">设备属性</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="有子设备" prop="parental">
                <el-switch 
                  v-model="form.parental" 
                  active-value="1" 
                  inactive-value="0"
                  active-text="是" 
                  inactive-text="否">
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="父设备ID" prop="parentId">
                <el-input v-model="form.parentId" placeholder="父设备ID" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="保密属性" prop="secrecy">
                <el-select v-model="form.secrecy" placeholder="选择保密属性">
                  <el-option label="不涉密" value="0"></el-option>
                  <el-option label="涉密" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="安全模式" prop="safetyWay">
                <el-select v-model="form.safetyWay" placeholder="选择安全模式">
                  <el-option label="不采用" value="0"></el-option>
                  <el-option label="S/MIME签名" value="2"></el-option>
                  <el-option label="S/MIME加密签名" value="3"></el-option>
                  <el-option label="数字摘要" value="4"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="注册方式" prop="registerWay">
                <el-select v-model="form.registerWay" placeholder="选择注册方式">
                  <el-option label="RFC3261标准" value="1"></el-option>
                  <el-option label="口令双向认证" value="2"></el-option>
                  <el-option label="数字证书双向认证" value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="证书有效" prop="certifiable">
                <el-switch 
                  v-model="form.certifiable" 
                  active-value="1" 
                  inactive-value="0"
                  active-text="有效" 
                  inactive-text="无效">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加视频播放器组件 -->
    <devicePlayer ref="devicePlayer" />
  </div>
</template>

<script>
import { listWvpDeviceChannel, getWvpDeviceChannel, delWvpDeviceChannel, addWvpDeviceChannel, updateWvpDeviceChannel } from "@/api/system/wvpDeviceChannel";
import { wvpLogin, startPlay as wvpStartPlay } from "@/utils/wvpRequest";
import devicePlayer from "@/components/DevicePlayer";

export default {
  name: "WvpDeviceChannel",
  components: {
    devicePlayer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // WVP相关状态
      wvpAccessToken: null,
      isWvpLoggedIn: false,
      playLoading: false,
      // 卡片选择状态
      selectedChannels: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 国标28181设备通道表格数据
      wvpDeviceChannelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        name: null,
        manufacturer: null,
        model: null,
        owner: null,
        civilCode: null,
        block: null,
        address: null,
        parental: null,
        parentId: null,
        safetyWay: null,
        registerWay: null,
        certNum: null,
        certifiable: null,
        errCode: null,
        endTime: null,
        secrecy: null,
        ipAddress: null,
        port: null,
        password: null,
        status: null,
        longitude: null,
        latitude: null,
        ptzType: null,
        positionType: null,
        roomType: null,
        useType: null,
        supplyLightType: null,
        directionType: null,
        resolution: null,
        businessGroupId: null,
        downloadSpeed: null,
        svcSpaceSupportMod: null,
        svcTimeSupportMode: null,
        subCount: null,
        streamId: null,
        hasAudio: null,
        gpsTime: null,
        streamIdentification: null,
        channelType: null,
        gbDeviceId: null,
        gbName: null,
        gbManufacturer: null,
        gbModel: null,
        gbOwner: null,
        gbCivilCode: null,
        gbBlock: null,
        gbAddress: null,
        gbParental: null,
        gbParentId: null,
        gbSafetyWay: null,
        gbRegisterWay: null,
        gbCertNum: null,
        gbCertifiable: null,
        gbErrCode: null,
        gbEndTime: null,
        gbSecrecy: null,
        gbIpAddress: null,
        gbPort: null,
        gbPassword: null,
        gbStatus: null,
        gbLongitude: null,
        gbLatitude: null,
        gbBusinessGroupId: null,
        gbPtzType: null,
        gbPositionType: null,
        gbRoomType: null,
        gbUseType: null,
        gbSupplyLightType: null,
        gbDirectionType: null,
        gbResolution: null,
        gbDownloadSpeed: null,
        gbSvcSpaceSupportMod: null,
        gbSvcTimeSupportMode: null,
        recordPlanId: null,
        dataType: null,
        dataDeviceId: null,
        gpsSpeed: null,
        gpsAltitude: null,
        gpsDirection: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
        channelType: [
          { required: true, message: "通道类型(0-未知,1-视频,2-音频,3-物联网通道)不能为空", trigger: "change" }
        ],
        dataType: [
          { required: true, message: "数据类型不能为空", trigger: "change" }
        ],
        dataDeviceId: [
          { required: true, message: "数据设备ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.loginToWvp();
  },
  methods: {
    /** 自动登录WVP平台 */
    loginToWvp() {
      if (this.isWvpLoggedIn) return;
      console.log("WVP通道页面：尝试自动登录WVP平台...");
      wvpLogin('admin', '6f1db4f72b187835d9ac5068223ad822')
        .then(res => {
          if (res.data && res.data.accessToken) {
            this.wvpAccessToken = res.data.accessToken;
            this.isWvpLoggedIn = true;
            console.log("WVP通道页面：WVP-GB28181-Pro 自动登录成功");
            this.$message.success("WVP平台连接成功");
          } else {
            throw new Error(res.msg || "登录失败，未获取到访问令牌");
          }
        })
        .catch(err => {
          console.error("WVP通道页面：WVP自动登录错误:", err);
          this.$message.error("WVP平台连接失败: " + (err.message || "未知错误"));
        });
    },
    /** 播放视频按钮操作 */
    handlePlay(row) {
      // 检查登录状态
      if (!this.isWvpLoggedIn) {
        this.$message.error('WVP平台未连接，请稍后重试');
        return;
      }

      console.log("准备播放通道视频:", row);
      
      // 获取设备ID和通道ID
      const deviceId = row.deviceId;
      const channelId = row.channelId || row.deviceId;
      
      if (!deviceId || !channelId) {
        this.$message.error('设备ID或通道ID不能为空');
        return;
      }

      this.playLoading = true;
      
      // 调用WVP API开始播放
      wvpStartPlay(deviceId, channelId, { transport: 'TCP-ACTIVE' })
        .then(res => {
          console.log("获取视频流成功:", res);
          if (res.data) {
            // 构建完整的流信息
            const streamInfo = {
              app: res.data.app || "rtp",
              stream: res.data.stream || channelId,
              // 标准协议
              ws_flv: res.data.ws_flv,
              flv: res.data.flv,
              rtmp: res.data.rtmp,
              hls: res.data.hls,
              rtsp: res.data.rtsp,
              // 安全协议
              wss_flv: res.data.wss_flv,
              https_flv: res.data.https_flv,
              https_hls: res.data.https_hls,
              // WebRTC
              rtc: res.data.rtc,
              rtcs: res.data.rtcs,
              // FMP4
              fmp4: res.data.fmp4,
              ws_fmp4: res.data.ws_fmp4,
              // 媒体服务器信息
              mediaServerId: res.data.mediaServerId,
              // 添加设备和通道ID信息，用于云台控制
              deviceId: deviceId,
              channelId: channelId
            };
            
            console.log("视频流信息:", JSON.stringify(streamInfo));
            
            // 使用DevicePlayer组件播放视频
            this.$refs.devicePlayer.openDialog('media', deviceId, streamInfo, row.hasAudio === 1);
            console.log("视频播放器已打开");
          } else {
            throw new Error('未获取到视频流信息');
          }
        })
        .catch(error => {
          console.error("播放失败:", error);
          this.$message.error("播放失败: " + (error.message || "未知错误"));
        })
        .finally(() => {
          this.playLoading = false;
        });
    },
    /** 查询国标28181设备通道列表 */
    getList() {
      this.loading = true;
      listWvpDeviceChannel(this.queryParams).then(response => {
        this.wvpDeviceChannelList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 清空选择状态
        this.clearSelection();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceId: null,
        name: null,
        manufacturer: null,
        model: null,
        owner: null,
        civilCode: null,
        block: null,
        address: null,
        parental: null,
        parentId: null,
        safetyWay: null,
        registerWay: null,
        certNum: null,
        certifiable: null,
        errCode: null,
        endTime: null,
        secrecy: null,
        ipAddress: null,
        port: null,
        password: null,
        status: null,
        longitude: null,
        latitude: null,
        ptzType: null,
        positionType: null,
        roomType: null,
        useType: null,
        supplyLightType: null,
        directionType: null,
        resolution: null,
        businessGroupId: null,
        downloadSpeed: null,
        svcSpaceSupportMod: null,
        svcTimeSupportMode: null,
        createTime: null,
        updateTime: null,
        subCount: null,
        streamId: null,
        hasAudio: null,
        gpsTime: null,
        streamIdentification: null,
        channelType: null,
        gbDeviceId: null,
        gbName: null,
        gbManufacturer: null,
        gbModel: null,
        gbOwner: null,
        gbCivilCode: null,
        gbBlock: null,
        gbAddress: null,
        gbParental: null,
        gbParentId: null,
        gbSafetyWay: null,
        gbRegisterWay: null,
        gbCertNum: null,
        gbCertifiable: null,
        gbErrCode: null,
        gbEndTime: null,
        gbSecrecy: null,
        gbIpAddress: null,
        gbPort: null,
        gbPassword: null,
        gbStatus: null,
        gbLongitude: null,
        gbLatitude: null,
        gbBusinessGroupId: null,
        gbPtzType: null,
        gbPositionType: null,
        gbRoomType: null,
        gbUseType: null,
        gbSupplyLightType: null,
        gbDirectionType: null,
        gbResolution: null,
        gbDownloadSpeed: null,
        gbSvcSpaceSupportMod: null,
        gbSvcTimeSupportMode: null,
        recordPlanId: null,
        dataType: null,
        dataDeviceId: null,
        gpsSpeed: null,
        gpsAltitude: null,
        gpsDirection: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 卡片选择相关方法 */
    // 切换通道选择状态
    toggleChannelSelection(channel) {
      const index = this.selectedChannels.findIndex(c => c.id === channel.id);
      if (index > -1) {
        this.selectedChannels.splice(index, 1);
      } else {
        this.selectedChannels.push(channel);
      }
      this.updateSelectionState();
    },
    // 检查通道是否已选择
    isChannelSelected(channel) {
      return this.selectedChannels.some(c => c.id === channel.id);
    },
    // 清空选择
    clearSelection() {
      this.selectedChannels = [];
      this.updateSelectionState();
    },
    // 更新选择状态
    updateSelectionState() {
      this.ids = this.selectedChannels.map(item => item.id);
      this.single = this.selectedChannels.length !== 1;
      this.multiple = this.selectedChannels.length === 0;
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedChannels.length === 0) {
        this.$message.warning('请至少选择一个通道');
        return;
      }
      const channelNames = this.selectedChannels.map(c => c.name || c.deviceId).join('、');
      this.$modal.confirm(`是否确认删除通道：${channelNames}？`).then(() => {
        const ids = this.selectedChannels.map(c => c.id);
        return delWvpDeviceChannel(ids);
      }).then(() => {
        this.getList();
        this.clearSelection();
        this.$modal.msgSuccess("批量删除成功");
      }).catch(() => {});
    },
    // 获取通道类型文本
    getChannelTypeText(type) {
      const typeMap = {
        '0': '未知',
        '1': '视频',
        '2': '音频',
        '3': '物联网'
      };
      return typeMap[type] || type || '-';
    },
    // 获取通道类型颜色
    getChannelTypeColor(type) {
      const colorMap = {
        '0': 'info',
        '1': 'success',
        '2': 'warning',
        '3': 'primary'
      };
      return colorMap[type] || 'info';
    },
    // 获取云台类型文本
    getPtzTypeText(type) {
      const typeMap = {
        '0': '未知',
        '1': '球机',
        '2': '半球',
        '3': '固定',
        '4': '遥控'
      };
      return typeMap[type] || type || '-';
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加国标28181设备通道";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWvpDeviceChannel(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改国标28181设备通道";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWvpDeviceChannel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWvpDeviceChannel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除国标28181设备通道编号为"' + ids + '"的数据项？').then(function() {
        return delWvpDeviceChannel(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/wvpDeviceChannel/export', {
        ...this.queryParams
      }, `wvpDeviceChannel_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/* 卡片容器样式 */
.channel-cards-container {
  margin-top: 20px;
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

/* 通道卡片样式 */
.channel-card {
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.channel-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  border-color: #c0c4cc;
}

.channel-card.selected {
  border-color: #409eff;
  box-shadow: 0 6px 24px rgba(64, 158, 255, 0.25);
  background: #f0f9ff;
}

/* 卡片头部 */
.card-header {
  padding: 0;
}

.channel-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-content {
  flex: 1;
  min-width: 0;
}

.channel-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.channel-id {
  font-size: 11px;
  color: #909399;
}

.status-tag {
  flex-shrink: 0;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

/* 卡片内容 */
.card-content {
  padding: 0;
}

.info-section {
  margin-bottom: 12px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.info-section:last-child {
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 6px 0;
  font-size: 12px;
  font-weight: 600;
  color: #409eff;
  border-bottom: 1px solid #d0d7de;
  padding-bottom: 3px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4px 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3px 0;
  border-bottom: 1px solid #f0f0f0;
  min-height: 20px;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
  margin-right: 8px;
  min-width: 60px;
}

.value {
  font-size: 12px;
  color: #303133;
  text-align: right;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  font-weight: 500;
}

/* 卡片操作按钮 */
.card-actions {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 6px;
}

/* 批量操作样式 */
.batch-actions {
  margin-bottom: 20px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .cards-grid {
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 14px;
  }
}

@media (max-width: 768px) {
  .cards-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .channel-card {
    margin-bottom: 0;
  }
  
  .channel-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .status-tag {
    align-self: flex-end;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 2px;
    padding: 4px 0;
  }
  
  .value {
    text-align: left;
    width: 100%;
  }
  
  .card-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .channel-cards-container {
    margin-top: 15px;
  }
  
  .cards-grid {
    gap: 10px;
  }
  
  .channel-name {
    font-size: 14px;
  }
  
  .label, .value {
    font-size: 11px;
  }
  
  .section-title {
    font-size: 11px;
  }
}

/* Element UI 样式调整 */
.channel-card .el-card__header {
  padding: 12px 16px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  border-radius: 6px 6px 0 0;
}

.channel-card.selected .el-card__header {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-bottom: 1px solid #409eff;
}

.channel-card .el-card__body {
  padding: 12px;
  background: #ffffff;
}

.channel-card.selected .el-card__body {
  background: #fafcff;
}

.channel-card .el-checkbox {
  margin-right: 0;
}

.channel-card .el-tag {
  border: none;
  font-weight: 500;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 动画效果 */
.channel-card {
  animation: fadeInUp 0.3s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 确保卡片选择时有视觉反馈 */
.channel-card.selected .channel-name {
  color: #409eff;
  text-shadow: 0 1px 2px rgba(64, 158, 255, 0.1);
}

.channel-card.selected .section-title {
  color: #1976d2;
}

.channel-card.selected .info-section {
  background: #f0f9ff;
  border-color: #bbdefb;
}
</style>
